package fr.cephb.operon.common;

import java.io.IOException;
import java.io.PrintStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;


public abstract class HttpApplication extends CmdLineApplication
implements HttpHandler
{
public static final int DEFAULT_PORT=8070;
protected int port=DEFAULT_PORT;
	
public abstract void handle(HttpExchange exchange) throws IOException;

protected static class Parameter
	{
	private String name;
	private String value;
	Parameter(String name,String value)
		{
		this.name=name;
		this.value=value;
		}
	
	public String getName() {
		return name;
	}
	
	public String getValue() {
		return value;
	}
	}

public int getPort() {
	return port;
}


public List<Parameter> getParameters(HttpExchange http) throws IOException
	{
	List<Parameter> params= new ArrayList<Parameter>();
	String query=null;
	if(http.getRequestMethod().equalsIgnoreCase("GET"))
		{
		query= http.getRequestURI().getRawQuery();
		}
	else
		{
		throw new IOException("Unsupported Method:"+http.getRequestMethod());
		}
	
	if(query!=null)
		{
		for(String s:query.split("[&]"))
	        {
	        s=s.replace('+', ' ');
	        int eq= s.indexOf('=');
	        if(eq>0)
	            {
	            params.add(new Parameter(
	            	URLDecoder.decode(s.substring(0,eq),"UTF-8"),
	                URLDecoder.decode(s.substring(eq+1),"UTF-8")
	                ));
	            }
	        }
		}
	
	return params;
	}


@Override
protected void usage(PrintStream out)
	{
	super.usage(out);
	out.println(" --port <port> default: "+port);
	}

@Override
protected int parseOption(String[] args, int optind)
	{
	int i= super.parseOption(args, optind);
	if(i!=-1) return i;
	//port
	if(args[optind].equals("--port"))
		{
		this.port= Integer.parseInt(args[++optind]);
		}
	else
		{
		return -1;
		}
	return optind;
	}

}
